package com.fengycx.templeate;

import com.fengycx.properties.FileUploadProp;
import com.fengycx.utils.AssertUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;
import com.qcloud.cos.region.Region;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;

@Configuration
public class FileUploadTemplate {

    private FileUploadProp fileUploadProp;

    public FileUploadTemplate(FileUploadProp fileUploadProp){
        this.fileUploadProp=fileUploadProp;
    }

    public COSClient getCosClient(){
        COSCredentials cred = new BasicCOSCredentials(fileUploadProp.getSecretId(), fileUploadProp.getSecretKey());
        Region region = new Region(fileUploadProp.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        return  cosClient;
    }


    public String uploadFile(InputStream file,String filePosition){
        PutObjectRequest putObjectRequest = new PutObjectRequest( fileUploadProp.getBucketName(), filePosition,file,new ObjectMetadata());
        COSClient cosClient = getCosClient();
        //上传图片
        cosClient.putObject(putObjectRequest);

        Boolean auditResult = isAudit(filePosition);
        AssertUtil.isTrue(auditResult,"图片不合规，请重新上传");
        // https://fengycx-0305-1324772510.cos.ap-chengdu.myqcloud.com/fengycx/1709634116111.jpg
        String url = String.format(fileUploadProp.getFilePosition(), fileUploadProp.getBucketName(), fileUploadProp.getRegion(), filePosition);
        return url;
    }

    public Boolean isAudit(String uploadPosition){
        //创建任务请求对象
        ImageAuditingRequest request = new ImageAuditingRequest();
        //请求参数见 API文档
        //设置请求Bucket
        request.setBucketName(fileUploadProp.getBucketName());
        //设置审核模型
        request.setDetectType(fileUploadProp.getDetectType());
        //设置图片位置
        request.setObjectKey(uploadPosition);
        //调用接口，获取任务响应对象
        COSClient cosClient = getCosClient();
        ImageAuditingResponse response = cosClient.imageAuditing(request);
        String result = response.getResult();
        if ("0".equals(result)){
            return true;
        }else{
            return false;
        }

    }

}
